package _8_Gorm框架老郭

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func main() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect darabase")
	}

	//Preload（子查询 ）
	//案例1：查询西游记的出版社名称
	var book01 = Bookl{Title: "西游记"}
	db.Where(&book01).Preload("Publish").Find(&book01)
	fmt.Println(book01)
	fmt.Println(book01.Publish.Name)

	//案例2：查询红与黑的出版社和作者名
	var book02 = Bookl{Title: "傲慢与偏见"}
	db.Where(&book02).Preload("Publish").Preload("Authors").Find(&book02)
	fmt.Println(book02)
	fmt.Println(book02.Publish.Name)
	fmt.Println(book02.Authors)

	//案例3：查询西游记的作者信息
	var book03 = Bookl{Title: "西游记"}
	db.Where(book03).Preload(clause.Associations).Find(&book03)
	fmt.Println(book03.Authors)

	//Joins查询 在一个单独查询中加载关联数据。而 Join Preload 会使用 inner join 加载关联数据
	//案例1：查询西游记的出版社名称
	var book04 = Bookl{Title: "西游记"}
	db.Joins("Publish").Find(&book04)
	fmt.Println(book04)
	fmt.Println(book04.Publish.Name)

	//案例2：查询西游记的作者名
	authors := []Author{}
	db.Table("Books").Select("books.*,authors.name").Joins("left join  book_authors on book_authors.book_id=books.id left join authors  on book_authors.author_id = authors.id").Where("books.title=?", "西游记").Find(&authors)
	fmt.Println(authors)
}
